import { _decorator, Component, Node, Prefab, Pool, director, instantiate } from 'cc';
import { Events } from '../events/Events';
import { Projectile } from './Projectile';
const { ccclass, property } = _decorator;

@ccclass('ProjectileEmitter')
export class ProjectileEmitter extends Component {
    @property(Prefab)
    public arrowPrefab: Prefab = null

    public pool: Pool<Node> = null

    start() {
        this.pool = new Pool(
            () => instantiate(this.arrowPrefab),
            5,
            (node: Node) => {
                node.removeFromParent()
            }
        )
    }

    onDestory() {
        this.pool.destroy()
    }
    public create(): Projectile {
        let node = this.pool.alloc()
        if (node.parent == null) {
            director.getScene().addChild(node)
        }
        let projectile = node.getComponent(Projectile)
        node.once(Events.OnPrejectileDead, this.onPrejectileDead, this)
        node.active = true
        return projectile
    }
    public onPrejectileDead(projectile: Projectile) {
        projectile.node.active = false
        this.pool.free(projectile.node)
    }
}


